--
-- Author: shineflag
-- Date: 2016-09-21 15:38:33
--

local skynet = require "skynet"
local service = require "service"
local client = require "client"
local log = require "log"
local proto = require("proto_json")

local TAG = "AUTH"


local auth = {}
local users = {}
local command = {}



--注册
function command.signup(cli, args )
	log.d(TAG,"signup userid[%s]",args.userid)
	if not users[args.userid] then
		users[args.userid] = cli 
		local resp = {ret = 0}
		local pkg = proto.create_resp("signup",resp)
		return pkg 
	else
		log.e(TAG,"Aready exist user[%s]",args.userid)
		return nil 
	end
end


function command.signin( cli,args )
	log.d(TAG,"signin userid[%s]",args.userid)
	if users[args.userid] then
		cli.userid = args.userid 
		cli.exit = true 
		local resp = {ret = 0}
		local pkg = proto.create_resp("signin",resp)
		return pkg 
	else
		log.d(TAG,"signin not userid[%s]",args.userid)
		local resp = {ret = 1}
		pkg = proto.create_resp("signin",resp)
		return pkg 
	end
end



local function ondata(cli,data)
	local info = proto.unpack(data)
	if info.cmd then
		local f = command[info.cmd] 
		if f then
			return f(cli,info.req)
		else
			log.e(TAg,"not proc to cmd[%s]",cmd)
		end
	else
		log.e(TAG,"not cmd data:",data)
	end

	return nil 
end

--验证握手
function auth.shakehand(fd)
	local cli = { name = "auth",fd = fd }
	cli.ondata = ondata
	local c = client.dispatch(cli)
	return c.userid
end


service.init {
	command = auth,
	info = users,
}